package loveqq.niceexcel.util;

import loveqq.niceexcel.converter.CellData;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaError;

import java.math.BigDecimal;

/**
 * 单元格工具类
 *
 * @author zhongjh@tsintergy.com
 * @date 2022-08-18
 */
public class CellUtils {
    private static final String EMPTY = "";

    /**
     * 获取单元格值数据
     *
     * @param cell 单元格
     * @return 单元格值数据
     */
    public static CellData<Object> getCellData(Cell cell) {
        CellData<Object> result = new CellData<>();
        if (cell == null || cell.getCellType() == null) {
            return result;
        }
        Object data;
        switch (cell.getCellType()) {
            case NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    data = cell.getDateCellValue();
                    result.setDateValue(cell.getDateCellValue());
                    result.setLocalDateTimeValue(cell.getLocalDateTimeCellValue());
                } else {
                    BigDecimal number = new BigDecimal(Double.toString(cell.getNumericCellValue()));
                    data = number;
                    result.setNumberValue(number);
                }
                break;
            case BOOLEAN:
                data = cell.getBooleanCellValue();
                result.setBooleanValue(cell.getBooleanCellValue());
                break;
            case FORMULA:
                data = cell.getCellFormula();
                result.setFormulaValue(cell.getCellFormula());
                break;
            case BLANK:
                data = EMPTY;
                result.setStringValue(EMPTY);
                break;
            case ERROR:
                final FormulaError error = FormulaError.forInt(cell.getErrorCellValue());
                final String errorText = (error == null) ? EMPTY : error.getString();
                data = errorText;
                result.setStringValue(errorText);
                break;
            default:
                data = cell.getStringCellValue();
                result.setStringValue(cell.getStringCellValue());
        }
        result.setData(data);
        result.setType(cell.getCellType());
        return result;
    }

}
